<?php

namespace lico\Runtime;

use lico\Tool\Log;
use lico\Tool\Exception\SmartyException;

use lico\Container;

class Error
{

    public static function init()
    {

        error_reporting(E_ALL);
        set_error_handler([__CLASS__, 'appError']);
        set_exception_handler([__CLASS__, 'appException']);
        register_shutdown_function([__CLASS__, 'appShutdown']);

        return true;
    }

    /**
     * Error Handler
     * @param  integer $errno   错误编号
     * @param  integer $errstr  详细错误信息
     * @param  string  $errfile 出错的文件
     * @param  integer $errline 出错行号
     * @param array    $errcontext
     * @throws ErrorException
     */
    public static function appError($errno, $errstr, $errfile = '', $errline = 0, $errcontext = [])
    {

        $data = [
            'level'=>1,
            'code'=>$errno,
            'msg'=>$errstr,
            'line'=>$errline,
            'file'=>$errfile,
        ];
        
        Log::save('all', $data);
        pe($data);
    }

    public static function appException($e)
    {
        
        if (!$e instanceof \Exception) {//
            $e = new SmartyException($e, 1);
        }

        if (get_class($e) == 'Exception') {
            $e = new SmartyException($e, 1);
        }
        
        $data = [
            'level'=>2,
            'code'=>$e->getCode(),
            'msg'=>$e->getMessage(),
            'line'=>$e->getLine(),
            'file'=>$e->getFile(),
        ];
        
        Log::save('all', $data);
    }

    public static function appShutdown()
    {

        $runtime =  round(microtime(true) - START_TIME, 10) ;
        $memory = number_format(( memory_get_usage()-START_MEM ) / 1024, 2);
        $included_files = get_included_files();
        // p($included_files);

        $nowtime = round(microtime(true), 5);
        $now = substr($nowtime, 0, 10);
        $ms = substr($nowtime, 10);

        $data = [
            'time'=>date('Y-m-d H:i:s', $now).$ms,
            'uri'=>Container::getBowl('lico\Runtime\Request')->uri(),
            'action'=>Container::getBowl('lico\Runtime\Request')->action(),
            'runtime'=> '运行时间：'.$runtime.' s,'.'内存消耗：'.$memory.' KB,'.'文件加载数：'.count($included_files),
        ];
        // p($data);
        Log::save('all', $data);
    }
}
